import {Component, ViewEncapsulation, ViewChild, Input, Output, EventEmitter} from '@angular/core';
import {FormGroup, AbstractControl, FormBuilder, Validators} from '@angular/forms';
import {IdeaService} from '../../../services/app.idea';
import {UserService} from '../../../services/app.user';
import {Utility} from '../../../services/app.utility';
import {AuthenticationHelper} from '../../../app.authentication';
import {BaThemeSpinner}  from '../../../theme/services';
import {Modal} from 'ngx-modal';
import {ImageCropperComponent, CropperSettings} from 'ng2-img-cropper';

@Component({
    selector: 'line-chart',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./lineChart.scss'],
    templateUrl: './lineChart.html'
})
export class LineChart {

    @Input()
    userId:string;
    @Output()
    notifyParent:EventEmitter<any> = new EventEmitter();
    public form:FormGroup;
    public profileUserFirstName:AbstractControl;
    public profileUserLastName:AbstractControl;
    public profileUserAddress:AbstractControl;
    public profileUserCity:AbstractControl;
    public profileUserState:AbstractControl;
    public profileUserCountry:AbstractControl;
    public profileUserAboutme:AbstractControl;
  //  public profileImagelocal:any = "http://144.214.55.144:3001";
  public profileImagelocal:any = 'http://45.79.103.182:5002';
    private uploadImage:boolean;
    private showEdit:boolean;
    public showMessage:boolean;
    public data:any = {};
    public activityList:any = {};
    public cropperSettings:CropperSettings;
    public profileData:any;
    public profileImage:any;
    public activityCount:any;
    public activities:any;
    public profileImageUser:any;
    public profileName:any;
    public profileEmail:any;
    public profileLocation:any;
    public profileLocationCity:any;
    public profileLocationCountry:any;
    public profileDate:any;
    public profileIdeaCount:any;
    public profileCommentCount:any;
    public profileVoteCount:any;
    public profileLikesCount:any;
    public commentsOnUsersIdea:any;
    public aboutMe:any;

    @ViewChild('Modal')
    private myModal:Modal;
    @ViewChild('cropper')
    public cropper:ImageCropperComponent;

    constructor(public utility:Utility, private spinner:BaThemeSpinner, private formGroups:FormBuilder, private authentication:AuthenticationHelper, private UserService:UserService, private IdeaService:IdeaService, private Utility:Utility) {
        this.form = formGroups.group({
            'profileUserFirstName': ['', Validators.compose([Validators.required])],
            'profileUserLastName': ['', Validators.compose([Validators.required])],
            'profileUserAddress': ['', []],
            'profileUserCity': ['', []],
            'profileUserState': ['', []],
            'profileUserCountry': ['', []],
            'profileUserAboutme': ['', []]
        });
        this.showEdit = true;
        this.profileUserFirstName = this.form.controls['profileUserFirstName'];
        this.profileUserLastName = this.form.controls['profileUserLastName'];
        this.profileUserAddress = this.form.controls['profileUserAddress'];
        this.profileUserCity = this.form.controls['profileUserCity'];
        this.profileUserState = this.form.controls['profileUserState'];
        this.profileUserCountry = this.form.controls['profileUserCountry'];
        this.profileUserAboutme = this.form.controls['profileUserAboutme'];

        this.cropperSettings = new CropperSettings();
        this.cropperSettings.width = 100;
        this.cropperSettings.height = 100;
        this.cropperSettings.croppedWidth = 100;
        this.cropperSettings.croppedHeight = 100;
        this.cropperSettings.canvasWidth = 400;
        this.cropperSettings.canvasHeight = 300;
        this.cropperSettings.noFileInput = true;
        this.uploadImage = true;
        this.activityList = {
            '_id': '',
            'skipItem': 0,
            'itemsperPage': 10,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };

        // call view profile function
        this.viewProfile();
    }

    // Notify Parent for Open Modal PopUp
    sendNotification(idea) {
        this.notifyParent.emit(idea);
    }

    // Function for set notification to user
    getNotified(idea) {
        this.getIdeaComments(idea);
    }

    // In function API call for get user profile info
    public viewProfile() {
        this.UserService.userProfile({}).subscribe(
            data => this.userProfilesucces(data, undefined),
            error => this.userProfilefail(error)
        );

    }

    // API call for get user profile
    public  getUserProfileData(id, skip, act):void {
        this.activities = [];
        this.activityList = {
            '_id': '',
            'skipItem': 0,
            'itemsperPage': 6,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };
        this.activityList._id = id;
        if (skip === undefined)
            skip = 0;
        this.activityList.skipItem = skip;
        this.UserService.userProfile(this.activityList).subscribe(
            data => this.userProfilesucces(data, act),
            error => this.userProfilefail(error)
        );
    }

    // Function call after user profile API success
    public  userProfilesucces(data, act) {
        this.profileData = data;
        this.profileImage = this.profileImagelocal + this.profileData.profile.profileImageURL.slice(1);
        this.profileImageUser = this.profileImagelocal + this.profileData.profile.profileImageURL.slice(1);
        if (data.profile.firstName != 'undefined' && data.profile.firstName)
            this.profileName = this.profileData.profile.firstName + ' ';
        if (data.profile.lastName != 'undefined' && data.profile.lastName)
            this.profileName += this.profileData.profile.lastName;
        this.profileEmail = this.profileData.profile.email;
        this.profileLocation = this.profileData.profile.address;
        this.profileLocationCity = this.profileData.profile.city + ((this.profileData.profile.city.toString().length > 0 && this.profileData.profile.state.toString().length > 0 ) ? (', ' + this.profileData.profile.state) : (' ' + this.profileData.profile.state));
        this.profileLocationCountry = this.profileData.profile.country;
        this.profileDate = this.Utility.getFormattedDate(this.profileData.profile.createdAt);
        this.profileIdeaCount = this.profileData.ideaCount;
        this.profileCommentCount = this.profileData.commentCount;
        this.profileVoteCount = this.profileData.voteCount;
        this.profileLikesCount = this.profileData.likesCount;
        this.commentsOnUsersIdea = data.commentsOnUsersIdea;
        this.aboutMe = this.profileData.profile.aboutMe;

        // For activity log
        if (act === undefined) {
            this.activities = data.activity;
        } else {
            this.activities = act.concat(data.activity);
        }
        if (data.activity) {
            this.activityCount = data.activity.length;
        }
        if (data.activity.length > 0) {
            this.showMessage = false;
        } else {
            this.showMessage = true;
        }

    }

    // Function call after user profile failed
    public userProfilefail(error) {
        this.spinner.hideProgress();
    }

    //  Convert Date to MM/DD/YY
    public formateDate(dates):any {
        return this.utility.getFormattedDate(dates);
    }

    // Function for get formated date
    public formateDatewithTime(dates):any {
        return this.utility.getAgoDate(this.utility.getFormattedDate(dates));
    }

    // Function for get more activities
    public getMoreActivity(act) {
        this.activityList.skipItem += this.activityList.itemsperPage;
        this.getUserProfileData(this.profileData.profile._id, this.activityList.skipItem, act);
    }

    // Function for idea comment success
    public getIdeaComments(data) {
        this.spinner.hideProgress();
    }
}
